<?php

namespace App\Admin\Extensions\Tools;

use Encore\Admin\Admin;
use Encore\Admin\Grid\Tools\AbstractTool;
use Illuminate\Support\Facades\Request;

class AjaxButton extends AbstractTool
{
    public $buttons;

    public function __construct($buttons)
    {
        $this->buttons = $buttons;
    }

    public function script()
    {
        $url = Request::fullUrlWithQuery([]);
        return <<<EOT
$('input:radio.ajax-button').change(function () {
    var url = "$url";
    console.log($(this).val());
    $.ajax({ url: $(this).val(), dataType: 'json', success: function(data) {
        if(data.code == 0) {
            $.pjax({container:'#pjax-container', url: url});
        } else {
            alert(data.message);
        }
    }});
});
EOT;
    }

    public function render()
    {
        Admin::script($this->script());
        return view('admin.tools.ajax_button', ['buttons' => $this->buttons]);
    }
}